#include "stm32f10x.h"                  // Device header

/**
  * @brief		输入捕获模块初始化
  * @parm		无
  * @retval		无
  */
void IC_Init(void)
{
	//开启时钟
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	
	//配置GPIO
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	//配置内部时钟
	TIM_InternalClockConfig(TIM3);

	//配置时基单元
	TIM_TimeBaseInitTypeDef TIM_InitStructure;
	TIM_InitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_InitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_InitStructure.TIM_Period = 65535 - 1;
	TIM_InitStructure.TIM_Prescaler = 72 - 1;
	TIM_InitStructure.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM3, &TIM_InitStructure);
	
	//配置输入捕获
	TIM_ICInitTypeDef TIM_ICInitStructure;
	TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;					//CH通道
	TIM_ICInitStructure.TIM_ICFilter = 0x0F;							//滤波频率
	TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;			//极性，上升沿/下降沿触发
	TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;				//预分频，此处选择不分频
	TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;	//输入信号交叉，选择交叉
	TIM_ICInit(TIM3, &TIM_ICInitStructure);
	//PWMI配置
	//会将另一个通道配置成相反的配置
	TIM_PWMIConfig(TIM3, &TIM_ICInitStructure);
	
	//选择触发模式
	TIM_SelectInputTrigger(TIM3, TIM_TS_TI1FP1);					//触发源选择TI1FP1
	TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Reset);					//从模式选择复位
	
	//开启定时器
	TIM_Cmd(TIM3, ENABLE);
}

/**
  * @brief		基于时基单元设置的分频值，获取频率
  * @parm		无
  * @retval		频率
  */
uint32_t IC_GetFrequency(void)
{
	return 1000000 / (TIM_GetCapture1(TIM3) + 1);
}

/**
  * @brief		获取占空比
  * @parm		无
  * @retval		占空比   范围：0 ~ 99
  */
uint8_t IC_GetDuty(void)
{
	return (TIM_GetCapture2(TIM3) + 1) * 100 / (TIM_GetCapture1(TIM3) + 1);
}
